import React, { useEffect, useState, useCallback } from 'react'
import { get } from '../../api/index'
import { Tabs } from 'antd-mobile'
import styles from './Index.module.scss'
// import Myheader from '../../components/MyHeader/Index'
import { useSearchParams } from 'react-router-dom'
import { Image, Avatar } from 'antd-mobile'
// import { LeftOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import messageIcon from '../../../public/Icon/information_black_s.png'
import userIcon from '../../../public/Icon/user.png'
interface Dept { id: number; departmentName: string }
interface DoctorItem {
  doctorId: number
  doctorName: string
  imagePic?: string
  jobTitle?: string
  inauguralHospital?: string
  praise?: number
  serverNum?: number
  servicePrice?: number
  praiseNum?: number
  badNum?: number
}

const Index: React.FC = () => {
  const [searchParams] = useSearchParams()
  const [departmentList, setDepartmentList] = useState<Dept[]>([])
  const [activeDeptId, setActiveDeptId] = useState<number | null>(null)
  const [doctorList, setDoctorList] = useState<DoctorItem[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [condition, setCondition] = useState<number>(1)
  const [priceAsc, setPriceAsc] = useState<boolean>(false)
  const [selectedDoctor, setSelectedDoctor] = useState<DoctorItem | null>(null)
  const [thumbPage, setThumbPage] = useState<number>(0)
  const navigate = useNavigate()
  const getDepartmentList = useCallback(async () => {
    const res = await get('/api/health/share/knowledgeBase/v1/findDepartment', {})
    if (res.status === 200) {
      const list: Dept[] = res.data.result || []
      setDepartmentList(list)

      // 检查URL参数中是否有指定的科室
      const deptParam = searchParams.get('dept')
      if (deptParam && list.length > 0) {
        // 查找匹配的科室
        const matchedDept = list.find(dept =>
          dept.departmentName === deptParam ||
          dept.departmentName.includes(deptParam) ||
          deptParam.includes(dept.departmentName)
        )
        if (matchedDept) {
          setActiveDeptId(matchedDept.id)
        } else {
          // 如果没有找到匹配的科室，使用第一个
          setActiveDeptId(list[0].id)
        }
      } else if (list.length) {
        setActiveDeptId(list[0].id)
      }
    }
  }, [searchParams])

  const getDoctorList = useCallback(async (deptId: number, page: number = 1, count: number = 10) => {
    try {
      setLoading(true)
      const res = await get('/api/health/user/inquiry/v1/findDoctorList', {
        deptId,
        condition,
        ...(condition === 4 ? { sortBy: priceAsc ? 1 : 0 } : {}),
        page,
        count,
      })
      if (res.status === 200) {
        const list: DoctorItem[] = res.data.result || []
        setDoctorList(list)
        setSelectedDoctor(list[0] || null)
        setThumbPage(0)
      } else {
        setDoctorList([])
        setSelectedDoctor(null)
      }
    } finally {
      setLoading(false)
    }
  }, [condition, priceAsc])

  useEffect(() => {
    getDepartmentList()
  }, [getDepartmentList])

  useEffect(() => {
    if (activeDeptId) getDoctorList(activeDeptId)
  }, [activeDeptId, getDoctorList])

  const handleConditionClick = (c: number) => {
    if (c === 4) {
      if (condition === 4) {
        setPriceAsc(prev => !prev)
      } else {
        setCondition(4)
        setPriceAsc(false)
      }
    } else {
      setCondition(c)
    }
  }

  return (
    <div className={styles.page}>

      <div className={styles.stickyTabs}>
        <div className="header-top">
          <div className="back-button" onClick={() => navigate(-1)}> <Avatar
            src={userIcon}
            className="home-user-avatar"
          /></div>
          <div className="notification-bell"> <Image
            src={messageIcon}
            width={24}
            height={24}
            className="notification-icon"
          /></div>
        </div>
        <Tabs activeKey={activeDeptId?.toString()} onChange={key => setActiveDeptId(Number(key))}>
          {departmentList.map(d => (
            <Tabs.Tab title={d.departmentName} key={d.id.toString()} />
          ))}
        </Tabs>
      </div>

      {/* 排序条 */}
      <div className={styles.sortBar}>
        {[{ k: 1, t: '综合' }, { k: 2, t: '好评' }, { k: 3, t: '咨询数' }, { k: 4, t: '价格' }].map(it => (
          <div
            key={it.k}
            onClick={() => handleConditionClick(it.k)}
            className={`${styles.sortItem} ${condition === it.k ? styles.sortItemActive : ''}`}
            style={{ marginRight: `${it.k === 4 ? '0px' : '20px'}` }}
          >
            <span>{it.t}</span>
            {it.k === 4 && (
              <span className={styles.priceArrow}>{priceAsc ? '▲' : '▼'}</span>
            )}
          </div>
        ))}
      </div>

      {loading ? (
        <div className={styles.loading}>加载中...</div>
      ) : (
        <div className={styles.content}>
          {selectedDoctor ? (
            <div className={styles.card}>
              <div className={styles.cardImgWrap}>
                <img src={selectedDoctor.imagePic || ''} alt={selectedDoctor.doctorName} className={styles.cardImg} />
              </div>
              <div className={styles.cardInfoRow} style={{ display: "block" }}>
                <div className={styles.cardInfoMain}>
                  <div className={styles.cardTitle}>{selectedDoctor.doctorName}</div>
                  <div className={styles.cardSub}>{selectedDoctor.jobTitle || ''} · {selectedDoctor.inauguralHospital || ''}</div>
                  <div className={styles.cardMeta}>好评率 {selectedDoctor.praise ?? 0}% · 服务患者数 {selectedDoctor.serverNum ?? 0}</div>
                </div>
                <div className={styles.priceBox}>
                  <div className={styles.price}>{(selectedDoctor.servicePrice ?? 0)}H币/次</div>
                  <button className={styles.consultBtn}>立即咨询</button>
                </div>
              </div>
            </div>
          ) : (
            <div className={styles.empty}>暂无医生数据</div>
          )}

          {doctorList.length > 0 && (
            <div className={styles.thumbsWrap}>
              <div className={styles.thumbsRow}>
                <button className={styles.navBtn} onClick={() => setThumbPage(p => Math.max(0, p - 1))}>{'《'}</button>
                <div className={styles.thumbsList}>
                  {doctorList.slice(thumbPage * 3, thumbPage * 3 + 3).map(doc => (
                    <div key={`thumb-${doc.doctorId}`} className={styles.thumbCard} onClick={() => setSelectedDoctor(doc)}>
                      <div className={styles.thumbImgBox}>
                        <img src={doc.imagePic || ''} alt={doc.doctorName} className={styles.thumbImg} />
                      </div>
                      <div className={styles.thumbName}>{doc.doctorName}</div>
                    </div>
                  ))}
                </div>
                <button className={styles.navBtn} onClick={() => setThumbPage(p => Math.min(Math.max(0, Math.ceil(doctorList.length / 3) - 1), p + 1))}>{'》'}</button>
              </div>
              <div className={styles.pager}>
                {Math.min(thumbPage + 1, Math.max(1, Math.ceil(doctorList.length / 3)))} / {Math.max(1, Math.ceil(doctorList.length / 3))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default Index
